<script setup>
import { ref, onMounted, reactive } from "vue"; // 新增onMounted
import { getProductImageList } from "@/api/productImage";
import { getProductDetail } from "@/api/product";
import { addOrder } from "@/api/order";
import { pay } from "@/api/pay";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";

const userStore = useUserStore();
// 抽屉开关
const visibleDrawer = ref(false);
// 对话框开关
const dialogFormVisible = ref(false);

// 存储商品数据
const productData = ref({});

// 存储商品图片
const productImages = ref([]);

// 生成订单请求参数
const orderParams = ref({
  productId: null,
  quantity: 0,
  shippingAddress: "",
  receiptName: "",
  receiptPhone: "",
});
// 表单引用
const form = ref(null);

// 表单验证规则
const formRules = reactive({
  receiptName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  receiptPhone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  shippingAddress: [{ required: true, message: "请输入地址", trigger: "blur" }],
});

// 新增：当前轮播图索引
const currentSlide = ref(0);
// 新增：轮播图组件引用
const carousel = ref(null);

const handleOpen = async (data) => {
  visibleDrawer.value = true;
  const product = await getProductDetail(data.productId);
  productData.value = product.data.data;
  const res = await getProductImageList(data.productId);
  productImages.value = res.data.data || [];
  // 重置轮播图索引
  currentSlide.value = 0;
};

// 下单
const handleSubmit = () => {
  // 先判断是否登录了
  if (!userStore.token) {
    ElMessage({
      type: "error",
      message: "请先登录",
    });
    return;
  }
  orderParams.value.productId = productData.value.productId;
  dialogFormVisible.value = true;
};
// 购买
const purchase = async () => {
  // 表单预校验
  form.value.validate();
  console.log(orderParams.value);

  // 生成订单
  const order = await addOrder(orderParams.value);
  // 换取订单编号
  const orderId = order.data.data;

  // 关闭
  dialogFormVisible.value = false;
  // 确认订单
  open(orderId);
};

// 消息弹出框
const open = (orderId) => {
  ElMessageBox.confirm(
    `<div style="width: 400px;">
      <table style="width: 100%; border-collapse: separate; border-spacing: 8px 12px;">
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">订单编号</td>
          <td style="text-align: left;">${orderId || "暂无编号"}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">商品名称</td>
          <td style="text-align: left;">${
            productData.value.productName || "商品名称"
          }</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">购买数量</td>
          <td style="text-align: left;">${orderParams.value.quantity || 0}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">单价</td>
          <td style="text-align: left;">¥${productData.value.price}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">姓名</td>
          <td style="text-align: left;">${orderParams.value.receiptName}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">手机号</td>
          <td style="text-align: left;">${orderParams.value.receiptPhone}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">地址</td>
          <td style="text-align: left;">${
            orderParams.value.shippingAddress
          }</td>
        </tr>
      </table>
    </div>`,
    "是否确认支付",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      console.log(orderId);
      zf(orderId);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};

// 确认支付
const zf = async (orderId) => {
  try {
    const res = await pay(orderId);
    const loading = ElLoading.service({
      lock: true,
      text: "正在跳转支付页面...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    if (res && res.data) {
      // 创建临时div存放表单
      const div = document.createElement("div");
      div.innerHTML = res.data;
      document.body.appendChild(div);

      // 查找表单
      const form = div.querySelector("form");
      if (!form) {
        ElMessage.error("未找到支付表单，无法跳转");
        loading.close();
        document.body.removeChild(div);
        return false;
      }

      // 记录跳转前的时间和状态
      const jumpStartTime = Date.now();
      let isJumped = false;

      // 监听页面 visibility 变化，判断是否离开当前页面
      const handleVisibilityChange = () => {
        if (document.hidden) {
          isJumped = true;
          ElMessage.success("已跳转到支付页面");
        }
      };
      document.addEventListener("visibilitychange", handleVisibilityChange);

      // 提交表单（跳转到支付宝）
      form.submit();

      // 定时检查是否跳转成功
      setTimeout(() => {
        document.removeEventListener(
          "visibilitychange",
          handleVisibilityChange
        );
        loading.close();
        document.body.removeChild(div);

        // 判断是否跳转成功
        if (!isJumped && Date.now() - jumpStartTime > 2000) {
          ElMessage.warning("跳转可能未成功，请检查网络或重试");
          return false;
        }
        return isJumped;
      }, 2000);
    } else {
      loading.close();
      ElMessage.error("支付数据异常，无法跳转");
      return false;
    }
  } catch (error) {
    console.error("支付请求失败:", error);
    ElMessage.error("支付请求失败，请重试");
    return false;
  }
};
// 关闭抽屉
const handleCancel = () => {
  visibleDrawer.value = false;
  // 清空数据
  productData.value = {};
  productImages.value = [];
  orderParams.value = {
    productId: null,
    quantity: 1,
    shippingAddress: "",
    receiptName: "",
    receiptPhone: "",
  };
  // 重置轮播图索引
  currentSlide.value = 0;
};

// 新增：处理轮播图切换事件
const handleCarouselChange = (index) => {
  currentSlide.value = index;
};

// 向外暴露的方法
defineExpose({
  handleOpen,
});
</script>
<template>
  <div class="product-detail-container">
    <el-drawer
      v-model="visibleDrawer"
      direction="btt"
      size="100%"
      @close="handleCancel"
      class="product-drawer"
    >
      <div class="main-content">
        <el-row :gutter="30">
          <!-- 商品图片轮播区 -->
          <el-col :span="15">
            <div class="carousel-container">
              <el-carousel
                ref="carousel"
                height="350px"
                motion-blur
                :interval="7000"
                indicator-position="none"
                @change="handleCarouselChange"
              >
                <el-carousel-item
                  v-for="(item, index) in productImages"
                  :key="item.imageId || index"
                >
                  <el-image
                    style="width: 100%; height: 100%"
                    :src="item.imageUrl"
                    fit="contain"
                    preview-teleported
                    :preview-src-list="productImages.map((img) => img.imageUrl)"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><icon-picture /></el-icon>
                        <span class="placeholder-text">暂无图片</span>
                      </div>
                    </template>
                  </el-image>
                </el-carousel-item>
              </el-carousel>

              <!-- 缩略图指示器 -->
              <div class="thumbnail-indicators">
                <div
                  v-for="(item, index) in productImages"
                  :key="item.imageId || index"
                  class="thumbnail-item"
                  :class="{ active: currentSlide === index }"
                  @click="carousel.setActiveItem(index)"
                >
                  <el-image
                    :src="item.imageUrl"
                    fit="contain"
                    style="width: 100%; height: 100%"
                  />
                </div>
              </div>
            </div>
          </el-col>

          <!-- 商品信息区 -->
          <el-col :span="9">
            <div class="product-info">
              <el-form v-model="productData" label-width="90px">
                <el-form-item>
                  <span class="product-name">{{
                    productData.productName || "商品名称"
                  }}</span>
                </el-form-item>

                <el-form-item class="product-price" label="单价:">
                  <span class="price-value"
                    >¥{{ productData.price?.toFixed(2) || "0.00" }}</span
                  >
                </el-form-item>

                <el-form-item
                  v-if="productData.stock !== undefined"
                  class="product-stock"
                  label="库存:"
                >
                  <span class="stock-value">{{ productData.stock }} 件</span>
                </el-form-item>

                <el-form-item label="购买数量" class="quantity-selector">
                  <el-input-number
                    v-model="orderParams.quantity"
                    :min="0"
                    :max="productData.stock"
                    :step="1"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="handleSubmit"
                    size="large"
                    class="submit-btn"
                    :disabled="!productData.productId"
                  >
                    立即下单
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>

        <!-- 商品描述区域 -->
        <div class="product-description">
          <h3 class="description-title">商品详情</h3>
          <div
            class="description-content"
            v-html="productData.description"
          ></div>
        </div>
      </div>
    </el-drawer>
  </div>

  <!-- 消息对话框 -->
  <el-dialog v-model="dialogFormVisible" title="订单" width="500">
    <el-form
      label-width="80px"
      :model="orderParams"
      :rules="formRules"
      ref="form"
    >
      <el-form-item label="商品名称">
        <span>{{ productData.productName || "商品名称" }}</span>
      </el-form-item>
      <el-form-item label="购买数量">
        <span>{{ orderParams.quantity }}</span>
      </el-form-item>
      <el-form-item label="单价">
        <span>¥{{ productData.price }}</span>
      </el-form-item>
      <el-form-item label="总价">
        <span>{{ orderParams.quantity * productData.price }}</span>
      </el-form-item>
      <el-form-item label="姓名" prop="receiptName">
        <el-input v-model="orderParams.receiptName"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="receiptPhone">
        <el-input v-model="orderParams.receiptPhone"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="shippingAddress">
        <el-input
          v-model="orderParams.shippingAddress"
          name="address"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="purchase"> 购买 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped>
/* 原有样式保持不变 */
:deep(.el-drawer__header) {
  background-color: #f5f5f5;
  margin-bottom: 0px !important;
}
:deep(.el-drawer__body) {
  background-color: #f5f5f5;
}
.product-drawer {
  --el-drawer-bg-color: #fafafa;
}

.drawer-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.main-content {
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 轮播图样式 */
.carousel-container {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  padding: 20px;
}

.image-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
}

.placeholder-text {
  margin-top: 15px;
  font-size: 14px;
}

/* 缩略图指示器 */
.thumbnail-indicators {
  display: flex;
  gap: 10px;
  padding: 15px 0 5px;
  overflow-x: auto;
  scrollbar-width: thin;
}

.thumbnail-item {
  border: 1px solid #ded6d6;
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  opacity: 0.7;
  transition: all 0.2s;
  flex-shrink: 0;
}

.thumbnail-item.active {
  opacity: 1;
  border: 2px solid #409eff;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息样式 */
.product-info {
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 8px;
  padding: 80px 20px 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.price-value {
  color: #ff4d4f;
  font-size: 26px;
  font-weight: 700;
}

.product-stock {
  margin-bottom: 30px !important;
  color: #666;
}

.stock-value {
  font-size: 16px;
  color: #52c41a;
}

.quantity-selector {
  margin-bottom: 40px !important;
}

.submit-btn {
  width: 50%;
  padding: 12px 0;
  font-size: 16px;
}

/* 商品描述样式 */
.product-description {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 1px 30px 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.description-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.description-content {
  color: #666;
  line-height: 1.8;
  font-size: 14px;
}

.description-content img {
  max-width: 100%;
  height: auto;
  margin: 15px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }

  .carousel-container {
    height: auto;
  }

  .el-carousel {
    height: 300px !important;
  }

  .product-name {
    font-size: 18px;
  }

  .product-description {
    padding: 20px 15px;
  }
}
</style>
